package net.javamine.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import net.javamine.util.ExceptionUtils;
import net.javamine.util.PropertiesUtils;

import org.apache.log4j.Logger;

import com.mysql.jdbc.Driver;

/**
 * HibernateForMySQLDAO基类
 * 
 * @author <a href="mailto: java_lht@163.com">Lht</a>
 * @since 2012-11-23
 * @version 1.0
 */
public class BaseJDBCForMySQLDao {
	
	private static Logger log = Logger.getLogger(BaseJDBCForMySQLDao.class);

	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection() {
		try {
			new Driver();
			Map<String, String> proMap = PropertiesUtils.readProperties("resources/system/jdbc.properties");
			Connection connection = DriverManager.getConnection(proMap.get("jdbc.url"), proMap.get("jdbc.username"), proMap.get("jdbc.password"));
			return connection;
		} catch (SQLException e) {
			ExceptionUtils.getExceptionMessage(log, e);
			return null;
		}

	}

	/**
	 * 关闭数据库连接
	 * @param resultSet
	 * @param preparedStatement
	 * @param connection
	 */
	public static void close(ResultSet resultSet,PreparedStatement preparedStatement, Connection connection) {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
		} catch (SQLException e) {
			ExceptionUtils.getExceptionMessage(log, e);
		} finally {
			try {
				if (preparedStatement != null) {
					preparedStatement.close();
				}
			} catch (SQLException e) {
				ExceptionUtils.getExceptionMessage(log, e);
			} finally {
				try {
					if (connection != null) {
						connection.close();
					}
				} catch (SQLException e) {
					ExceptionUtils.getExceptionMessage(log, e);
				}
			}
		}
	}

	/**
	 * 关闭数据库连接
	 * @param preparedStatement
	 * @param connection
	 */
	public static void close(PreparedStatement preparedStatement, Connection connection) {
		try {
			if (preparedStatement != null) {
				preparedStatement.close();
			}
		} catch (SQLException e) {
			ExceptionUtils.getExceptionMessage(log, e);
		} finally {
			try {
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				ExceptionUtils.getExceptionMessage(log, e);
			}
		}
	}

}
